<script setup lang="ts">
import { ref } from 'vue'
import axios from 'axios'

// 定义比赛项目接口
interface GameEvent {
  eventID?: number  // 编辑时需要
  gameID: number
  eventName: string
  category: string
  description: string
  eventTime: string
  location: string
  maxParticipants: number
  currentParticipants: number
  status: string
}

// 响应式数据
const gameEvent = ref<GameEvent>({
  gameID: 1,
  eventName: '',
  category: '',
  description: '',
  eventTime: '',
  location: '',
  maxParticipants: 0,
  currentParticipants: 0,
  status: '未开始'
})

const errorMessage = ref('')
const successMessage = ref('')
const gameId = ref<number|null>(null)
const isEditMode = ref(false)  // 是否为编辑模式

// 初始化组件数据
const init = (id: number) => {
  gameId.value = id
  gameEvent.value.gameID = id
}

// 初始化编辑数据
const initEdit = (event: GameEvent) => {
  gameEvent.value = { ...event }
  gameId.value = event.gameID
  isEditMode.value = true
}

// 暴露方法给父组件
defineExpose({
  init,
  initEdit
})

// 提交表单
const submitForm = async () => {
  try {
    const token = localStorage.getItem('token')
    
    // 无论编辑模式还是新建模式，都使用同一个后端路径
    const response = await axios.post('http://localhost:8080/event/save', gameEvent.value, {
      headers: {
        'token': token || ''
      }
    })
    
    if (response.data.success) {
      successMessage.value = isEditMode.value ? '比赛项目更新成功' : '比赛项目添加成功'
      errorMessage.value = ''
      
      // 触发事件通知父组件
      window.dispatchEvent(new CustomEvent('gameEventAdded'))
      
      // 成功后延迟一段时间再跳转回比赛项目列表
      setTimeout(() => {
        window.dispatchEvent(new CustomEvent('showGameEvent', {
          detail: { type: 'backToEventsList', gameId: gameId.value }
        }))
      }, 1000) // 延迟1秒，让用户看到成功消息
    } else {
      errorMessage.value = response.data.message || (isEditMode.value ? '更新失败' : '添加失败')
      successMessage.value = ''
    }
  } catch (err) {
    console.error(isEditMode.value ? '更新比赛项目失败:' : '添加比赛项目失败:', err)
    errorMessage.value = isEditMode.value ? '更新比赛项目失败，请稍后再试' : '添加比赛项目失败，请稍后再试'
    successMessage.value = ''
  }
}

// 返回上一页
const goBack = () => {
  window.dispatchEvent(new CustomEvent('showGameEvent', {
    detail: { type: 'backToEventsList', gameId: gameId.value }
  }))
}
</script>

<template>
  <div class="new-game-event">
    <div class="header">
      <h2>{{ isEditMode ? '编辑比赛项目' : '新增比赛项目' }}</h2>
      <button class="back-button" @click="goBack">返回项目列表</button>
    </div>
    
    <form @submit.prevent="submitForm" class="event-form">
      <div class="form-group">
        <label for="eventName">项目名称:</label>
        <input 
          id="eventName" 
          v-model="gameEvent.eventName" 
          type="text" 
          required 
          placeholder="请输入项目名称"
        />
      </div>
      
      <div class="form-row">
        <div class="form-group">
          <label for="category">项目类别:</label>
          <select 
            id="category" 
            v-model="gameEvent.category" 
            required
          >
            <option value="">请选择项目类别</option>
            <option value="田径">田径</option>
            <option value="球类">球类</option>
            <option value="水上">水上</option>
            <option value="趣味">趣味</option>
            <option value="体操">体操</option>
            <option value="格斗">格斗</option>
          </select>
        </div>
        
        <div class="form-group">
          <label for="eventTime">比赛时间:</label>
          <input 
            id="eventTime" 
            v-model="gameEvent.eventTime" 
            type="datetime-local" 
            required 
          />
        </div>
      </div>
      
      <div class="form-group">
        <label for="description">项目描述:</label>
        <textarea 
          id="description" 
          v-model="gameEvent.description" 
          required 
          placeholder="请输入项目描述"
        ></textarea>
      </div>
      
      <div class="form-group">
        <label for="location">比赛地点:</label>
        <input 
          id="location" 
          v-model="gameEvent.location" 
          type="text" 
          required 
          placeholder="请输入比赛地点"
        />
      </div>
      
      <div class="form-row">
        <div class="form-group">
          <label for="maxParticipants">最大参与人数:</label>
          <input 
            id="maxParticipants" 
            v-model.number="gameEvent.maxParticipants" 
            type="number" 
            min="1" 
            required 
          />
        </div>
        
        <div class="form-group">
          <label for="status">项目状态:</label>
          <select id="status" v-model="gameEvent.status" required>
            <option value="未开始">未开始</option>
            <option value="筹划中">筹划中</option>
            <option value="报名中">报名中</option>
            <option value="进行中">进行中</option>
            <option value="已结束">已结束</option>
          </select>
        </div>
      </div>
      
      <div v-if="errorMessage" class="message error">
        {{ errorMessage }}
      </div>
      
      <div v-if="successMessage" class="message success">
        {{ successMessage }}
      </div>
      
      <div class="form-actions">
        <button type="reset" class="reset-button">重置</button>
        <button type="submit" class="submit-button">{{ isEditMode ? '更新项目' : '添加项目' }}</button>
      </div>
    </form>
  </div>
</template>

<style scoped>
.new-game-event {
  padding: 20px;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 30px;
}

.header h2 {
  color: #333;
  margin: 0;
}

.back-button {
  background: #95a5a6;
  color: white;
  border: none;
  border-radius: 5px;
  padding: 10px 20px;
  font-size: 16px;
  cursor: pointer;
  transition: all 0.3s ease;
}

.back-button:hover {
  background: #7f8c8d;
  transform: translateY(-2px);
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.2);
}

.event-form {
  background: white;
  border-radius: 8px;
  padding: 30px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
  max-width: 800px;
  margin: 0 auto;
}

.form-group {
  margin-bottom: 20px;
  display: flex;
  align-items: center;
}

.form-row {
  display: flex;
  gap: 20px;
}

.form-row .form-group {
  flex: 1;
}

label {
  display: block;
  margin-bottom: 5px;
  font-weight: bold;
  color: #555;
  width: 120px;
  margin-right: 15px;
  margin-bottom: 0;
}

input, textarea, select {
  flex: 1;
  padding: 12px;
  border: 1px solid #ddd;
  border-radius: 5px;
  font-size: 16px;
  box-sizing: border-box;
}

textarea {
  min-height: 100px;
  resize: vertical;
}

.message {
  padding: 12px;
  border-radius: 5px;
  margin-bottom: 20px;
  text-align: center;
}

.error {
  background-color: #ffebee;
  color: #c62828;
  border: 1px solid #ffcdd2;
}

.success {
  background-color: #e8f5e9;
  color: #2e7d32;
  border: 1px solid #c8e6c9;
}

.form-actions {
  display: flex;
  justify-content: center;
  gap: 20px;
  margin-top: 30px;
}

.submit-button, .reset-button {
  padding: 12px 30px;
  font-size: 16px;
  border: none;
  border-radius: 5px;
  cursor: pointer;
  transition: all 0.3s ease;
}

.submit-button {
  background: linear-gradient(to right, #31B310, #2a990e);
  color: white;
}

.submit-button:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.2);
}

.reset-button {
  background: #95a5a6;
  color: white;
}

.reset-button:hover {
  background: #7f8c8d;
  transform: translateY(-2px);
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.2);
}

@media (max-width: 768px) {
  .form-row {
    flex-direction: column;
    gap: 0;
  }
  
  .form-group {
    flex-direction: column;
    align-items: flex-start;
  }
  
  label {
    margin-bottom: 5px;
    width: auto;
    margin-right: 0;
  }
  
  .event-form {
    padding: 20px;
  }
}
</style>